// the lock server implementation
using namespace std;

#include "lock_server.h"

lock_server::lock_server():
  nacquire (0)
{
}

lock_server::~lock_server()
{
}

lock_protocol::status
lock_server::stat(int clt, lock_protocol::lockid_t lid, int &r)
{
  lock_protocol::status ret = lock_protocol::OK;
  printf("stat request from clt %d\n", clt);
  r = nacquire;
  return ret;
}

//lock_protocol::status
//lock_server::acquire(int clt, lock_protocol::lockid_t lid, int &r)
//{
//	printf("In server_aquire!\n");
//	lock_protocol::status ret = lock_protocol::OK;
//	map<lock_protocol::lockid_t, short>::iterator it = lock_map.find(lid);
//
//	if (it != lock_map.end()) {
//		//Condwait until false, change bool to TRUE;
//		pthread_mutex_t mutex;
//		pthread_cond_wait(it->second = false, mutex);
//
//	}
//	else
//		lock_map[lid] = TRUE;
//	return ret;
//}

lock_protocol::status
lock_server::acquire(int clt, lock_protocol::lockid_t lid, int &r){
	// acquire
	pthread_mutex_lock(&mutex);
	printf("Hello, Server::acquire\n");
	map<lock_protocol::lockid_t, short>::iterator it;
	it = lock_map.find(lid);
	if (it == lock_map.end()){
	  //create new lock
	  lock_map[lid] = TRUE;
	}
	else {
		if (it->second == TRUE)
			pthread_cond_wait(&cond_mutex, &mutex);
	}
	it->second= TRUE;
	pthread_mutex_unlock(&mutex);
	return lock_protocol::OK;
}


lock_protocol::status
lock_server::release(int clt, lock_protocol::lockid_t lid, int &r)
{
	printf("In server_release!\n");
	lock_protocol::status ret = lock_protocol::OK;
	return ret;
}

